package com.hmdp.utils;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//拦截登录
public class LoginInterceptor implements HandlerInterceptor {

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.是否需要拦截(ThreadLocal中是否有用户)

        if (UserHolder.getUser() == null) {
            //没有，拦截
            response.setStatus(401);
            return false;
        }

        //有，放行
        return true;
    }


    //后置拦截器
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
